/**
 * 微信API测试工具
 * 用于测试微信小程序API的功能和兼容性
 */

/**
 * API测试结果状态
 */
export const TEST_STATUS = {
  SUCCESS: 'success',
  FAILED: 'failed',
  SKIPPED: 'skipped',
  ERROR: 'error'
}

/**
 * 微信API测试器
 */
class WechatApiTester {
  constructor() {
    this.testResults = {}
    this.isRunning = false
  }

  /**
   * 运行所有API测试
   */
  async runAllTests() {
    if (this.isRunning) {
      throw new Error('测试正在运行中')
    }

    this.isRunning = true
    this.testResults = {}

    console.log('开始微信API测试...')

    try {
      // 基础API测试
      await this.testBasicApis()
      
      // 登录相关API测试
      await this.testLoginApis()
      
      // 用户信息API测试
      await this.testUserInfoApis()
      
      // 系统信息API测试
      await this.testSystemInfoApis()
      
      // 设置API测试
      await this.testSettingApis()
      
      // 账号信息API测试
      await this.testAccountInfoApis()
      
      // 插件相关API测试
      await this.testPluginApis()
      
      const summary = this.generateTestSummary()
      console.log('微信API测试完成:', summary)
      
      return {
        success: true,
        summary,
        details: this.testResults
      }
    } catch (error) {
      console.error('API测试失败:', error)
      return {
        success: false,
        error: error.message,
        details: this.testResults
      }
    } finally {
      this.isRunning = false
    }
  }

  /**
   * 测试基础API
   */
  async testBasicApis() {
    const tests = [
      {
        name: 'wx对象存在性',
        test: () => {
          return typeof wx !== 'undefined'
        }
      },
      {
        name: 'wx.request可用性',
        test: () => {
          return typeof wx !== 'undefined' && typeof wx.request === 'function'
        }
      },
      {
        name: 'wx.showToast可用性',
        test: () => {
          return typeof wx !== 'undefined' && typeof wx.showToast === 'function'
        }
      }
    ]

    await this.runTestGroup('基础API', tests)
  }

  /**
   * 测试登录相关API
   */
  async testLoginApis() {
    const tests = [
      {
        name: 'wx.login可用性',
        test: () => {
          return typeof wx !== 'undefined' && typeof wx.login === 'function'
        }
      },
      {
        name: 'wx.checkSession可用性',
        test: () => {
          return typeof wx !== 'undefined' && typeof wx.checkSession === 'function'
        }
      },
      {
        name: 'wx.login功能测试',
        test: async () => {
          if (typeof wx === 'undefined' || typeof wx.login !== 'function') {
            return false
          }

          return new Promise((resolve) => {
            wx.login({
              timeout: 5000,
              success: (res) => {
                resolve(res.code && res.code.length > 0)
              },
              fail: () => {
                resolve(false)
              }
            })
          })
        }
      },
      {
        name: 'wx.checkSession功能测试',
        test: async () => {
          if (typeof wx === 'undefined' || typeof wx.checkSession !== 'function') {
            return false
          }

          return new Promise((resolve) => {
            wx.checkSession({
              success: () => {
                resolve(true)
              },
              fail: () => {
                // checkSession失败是正常的，因为可能没有登录
                resolve(true)
              }
            })
          })
        }
      }
    ]

    await this.runTestGroup('登录API', tests)
  }

  /**
   * 测试用户信息API
   */
  async testUserInfoApis() {
    const tests = [
      {
        name: 'wx.getUserInfo可用性',
        test: () => {
          return typeof wx !== 'undefined' && typeof wx.getUserInfo === 'function'
        }
      },
      {
        name: 'wx.getUserProfile可用性',
        test: () => {
          return typeof wx !== 'undefined' && typeof wx.getUserProfile === 'function'
        }
      },
      {
        name: 'wx.getSetting可用性',
        test: () => {
          return typeof wx !== 'undefined' && typeof wx.getSetting === 'function'
        }
      },
      {
        name: 'wx.getSetting功能测试',
        test: async () => {
          if (typeof wx === 'undefined' || typeof wx.getSetting !== 'function') {
            return false
          }

          return new Promise((resolve) => {
            wx.getSetting({
              success: (res) => {
                resolve(res.authSetting !== undefined)
              },
              fail: () => {
                resolve(false)
              }
            })
          })
        }
      }
    ]

    await this.runTestGroup('用户信息API', tests)
  }

  /**
   * 测试系统信息API
   */
  async testSystemInfoApis() {
    const tests = [
      {
        name: 'wx.getSystemInfo可用性',
        test: () => {
          return typeof wx !== 'undefined' && typeof wx.getSystemInfo === 'function'
        }
      },
      {
        name: 'wx.getSystemInfoSync可用性',
        test: () => {
          return typeof wx !== 'undefined' && typeof wx.getSystemInfoSync === 'function'
        }
      },
      {
        name: 'wx.getSystemInfoSync功能测试',
        test: () => {
          if (typeof wx === 'undefined' || typeof wx.getSystemInfoSync !== 'function') {
            return false
          }

          try {
            const systemInfo = wx.getSystemInfoSync()
            return systemInfo && systemInfo.platform && systemInfo.version
          } catch (error) {
            return false
          }
        }
      },
      {
        name: 'wx.getSystemInfo功能测试',
        test: async () => {
          if (typeof wx === 'undefined' || typeof wx.getSystemInfo !== 'function') {
            return false
          }

          return new Promise((resolve) => {
            wx.getSystemInfo({
              success: (res) => {
                resolve(res && res.platform && res.version)
              },
              fail: () => {
                resolve(false)
              }
            })
          })
        }
      }
    ]

    await this.runTestGroup('系统信息API', tests)
  }

  /**
   * 测试设置API
   */
  async testSettingApis() {
    const tests = [
      {
        name: 'wx.getSetting可用性',
        test: () => {
          return typeof wx !== 'undefined' && typeof wx.getSetting === 'function'
        }
      },
      {
        name: 'wx.openSetting可用性',
        test: () => {
          return typeof wx !== 'undefined' && typeof wx.openSetting === 'function'
        }
      }
    ]

    await this.runTestGroup('设置API', tests)
  }

  /**
   * 测试账号信息API
   */
  async testAccountInfoApis() {
    const tests = [
      {
        name: 'wx.getAccountInfoSync可用性',
        test: () => {
          return typeof wx !== 'undefined' && typeof wx.getAccountInfoSync === 'function'
        }
      },
      {
        name: 'wx.getAccountInfoSync功能测试',
        test: () => {
          if (typeof wx === 'undefined' || typeof wx.getAccountInfoSync !== 'function') {
            return false
          }

          try {
            const accountInfo = wx.getAccountInfoSync()
            return accountInfo && accountInfo.miniProgram && accountInfo.miniProgram.appId
          } catch (error) {
            return false
          }
        }
      }
    ]

    await this.runTestGroup('账号信息API', tests)
  }

  /**
   * 测试插件相关API
   */
  async testPluginApis() {
    const tests = [
      {
        name: 'wx.pluginLogin可用性',
        test: () => {
          return typeof wx !== 'undefined' && typeof wx.pluginLogin === 'function'
        }
      }
    ]

    await this.runTestGroup('插件API', tests)
  }

  /**
   * 运行测试组
   */
  async runTestGroup(groupName, tests) {
    console.log(`开始测试 ${groupName}...`)
    
    const groupResults = {
      groupName,
      tests: [],
      summary: {
        total: tests.length,
        success: 0,
        failed: 0,
        skipped: 0,
        error: 0
      }
    }

    for (const test of tests) {
      const result = await this.runSingleTest(test)
      groupResults.tests.push(result)
      
      // 更新统计
      groupResults.summary[result.status]++
    }

    this.testResults[groupName] = groupResults
    console.log(`${groupName} 测试完成:`, groupResults.summary)
  }

  /**
   * 运行单个测试
   */
  async runSingleTest(test) {
    const result = {
      name: test.name,
      status: TEST_STATUS.SKIPPED,
      message: '',
      details: null,
      duration: 0,
      timestamp: Date.now()
    }

    try {
      const startTime = Date.now()
      
      if (typeof test.test === 'function') {
        const testResult = await test.test()
        
        result.duration = Date.now() - startTime
        
        if (testResult === true) {
          result.status = TEST_STATUS.SUCCESS
          result.message = '测试通过'
        } else if (testResult === false) {
          result.status = TEST_STATUS.FAILED
          result.message = '测试失败'
        } else {
          result.status = TEST_STATUS.SUCCESS
          result.message = '测试通过'
          result.details = testResult
        }
      } else {
        result.status = TEST_STATUS.ERROR
        result.message = '测试函数无效'
      }
    } catch (error) {
      result.status = TEST_STATUS.ERROR
      result.message = error.message
      result.details = error.stack
    }

    return result
  }

  /**
   * 生成测试摘要
   */
  generateTestSummary() {
    const summary = {
      total: 0,
      success: 0,
      failed: 0,
      skipped: 0,
      error: 0,
      groups: Object.keys(this.testResults).length,
      issues: [],
      recommendations: []
    }

    // 统计所有测试结果
    Object.values(this.testResults).forEach(group => {
      summary.total += group.summary.total
      summary.success += group.summary.success
      summary.failed += group.summary.failed
      summary.skipped += group.summary.skipped
      summary.error += group.summary.error

      // 收集问题
      group.tests.forEach(test => {
        if (test.status === TEST_STATUS.FAILED || test.status === TEST_STATUS.ERROR) {
          summary.issues.push({
            group: group.groupName,
            test: test.name,
            status: test.status,
            message: test.message
          })
        }
      })
    })

    // 生成建议
    if (summary.failed > 0) {
      summary.recommendations.push(`有 ${summary.failed} 个测试失败，请检查相关API`)
    }

    if (summary.error > 0) {
      summary.recommendations.push(`有 ${summary.error} 个测试出错，请检查环境配置`)
    }

    if (summary.success / summary.total < 0.8) {
      summary.recommendations.push('API兼容性较低，建议升级微信版本或基础库')
    }

    return summary
  }

  /**
   * 获取特定测试结果
   */
  getTestResult(groupName, testName) {
    const group = this.testResults[groupName]
    if (!group) {
      return null
    }

    return group.tests.find(test => test.name === testName) || null
  }

  /**
   * 检查特定API是否可用
   */
  isApiAvailable(groupName, testName) {
    const result = this.getTestResult(groupName, testName)
    return result ? result.status === TEST_STATUS.SUCCESS : false
  }

  /**
   * 运行特定测试组
   */
  async runTestGroupByName(groupName) {
    const groupTests = {
      '基础API': this.testBasicApis.bind(this),
      '登录API': this.testLoginApis.bind(this),
      '用户信息API': this.testUserInfoApis.bind(this),
      '系统信息API': this.testSystemInfoApis.bind(this),
      '设置API': this.testSettingApis.bind(this),
      '账号信息API': this.testAccountInfoApis.bind(this),
      '插件API': this.testPluginApis.bind(this)
    }

    const testFunction = groupTests[groupName]
    if (!testFunction) {
      throw new Error(`未知的测试组: ${groupName}`)
    }

    await testFunction()
    return this.testResults[groupName]
  }

  /**
   * 获取所有测试结果
   */
  getAllTestResults() {
    return this.testResults
  }

  /**
   * 清除测试结果
   */
  clearResults() {
    this.testResults = {}
  }

  /**
   * 导出测试报告
   */
  exportTestReport() {
    const summary = this.generateTestSummary()
    
    return {
      timestamp: Date.now(),
      summary,
      details: this.testResults,
      environment: this.getEnvironmentInfo()
    }
  }

  /**
   * 获取环境信息
   */
  getEnvironmentInfo() {
    try {
      if (typeof wx !== 'undefined' && typeof wx.getSystemInfoSync === 'function') {
        const systemInfo = wx.getSystemInfoSync()
        return {
          platform: systemInfo.platform,
          version: systemInfo.version,
          system: systemInfo.system,
          SDKVersion: systemInfo.SDKVersion
        }
      }
    } catch (error) {
      console.error('获取环境信息失败:', error)
    }

    return {
      platform: 'unknown',
      version: 'unknown',
      system: 'unknown',
      SDKVersion: 'unknown'
    }
  }
}

// 创建单例实例
const wechatApiTester = new WechatApiTester()

// 导出函数
export const runAllApiTests = () => wechatApiTester.runAllTests()
export const runTestGroup = (groupName) => wechatApiTester.runTestGroupByName(groupName)
export const getTestResult = (groupName, testName) => wechatApiTester.getTestResult(groupName, testName)
export const isApiAvailable = (groupName, testName) => wechatApiTester.isApiAvailable(groupName, testName)
export const getAllTestResults = () => wechatApiTester.getAllTestResults()
export const exportTestReport = () => wechatApiTester.exportTestReport()

export default wechatApiTester 